package com.ceba.test.modules.filemanage.helper;

import java.io.File;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ceba.base.helper.LoggerHelper;
import com.ceba.base.utils.IDSFileUtils;
import com.ceba.base.utils.ToPdfUtils;
import com.ceba.cebautils.StringUtil;
import com.ceba.test.base.config.LogicPathUtil;
import com.ceba.test.modules.storage.logicService.StorageFileCacheManage;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ceba.test.base.configs.CebaPathUtil;
import com.ceba.test.modules.admin.entity.TemplateWord;

import abc.ID;
import abc.Result;
import abc.util.FileHelper;
import abc.util.StringUtils;
import abc.web.HttpContext;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

@SuppressWarnings("deprecation")
public class FileUploadDownLoadHelper {
	private static Logger logger = LoggerFactory.getLogger(FileUploadDownLoadHelper.class);
	private final static long fileUploadMaxSize = 1024 * 1024 * 1024;

	DiskFileItemFactory factory;
	ServletFileUpload upload;
	
	private void init(HttpServletRequest request,HttpSession session ) throws UnsupportedEncodingException{
		request.setCharacterEncoding("utf-8");
		File tempDir = new File(session.getServletContext().getRealPath("/") + "tmp");
		if (!tempDir.exists()) {
			tempDir.mkdir();
		}
		factory = new DiskFileItemFactory();
		// 设置内存可用的大小
		factory.setSizeThreshold(10240000);
		factory.setRepository(tempDir);
		upload = new ServletFileUpload(factory);// 设置单个文件的最大上传size
		upload.setFileSizeMax(fileUploadMaxSize);// 设置整个request的最大size
		upload.setSizeMax(fileUploadMaxSize);
	}
	
	public void upload(String filePath, HttpContext httpContext, Result result) {
		HttpServletRequest request = httpContext.getRequest();
		HttpSession session = httpContext.getRequest().getSession();
		
		if (!StringUtils.isNotNullAndEmpty(filePath)) {
			result.setResult(false);
		}
		else{
			try {
				init(request,session);
				List<FileItem> items = (List<FileItem>) upload.parseRequest(request);
				for (FileItem item : items) {
					if (!item.isFormField()) {
						item.write(new File(filePath));
						result.setResult(true);
						break;
					}
				}
			} catch (Exception e) {
				LoggerHelper.error(logger, e, "");
				result.setResult(false);
			}
		}
		
	}


	/**
	 * 上传文件
	 * @param dirPath 文件目录
	 * @param fileName 文件名，不带拓展名
	 * @param result
	 */
	@SuppressWarnings("rawtypes")
	public void  springUpload(String dirPath,String fileName, HttpServletRequest request, Result result) {
		if (!StringUtils.isNotNullAndEmpty(dirPath)) {
			result.setResult(false);
		}else{
			try {

				//将当前上下文初始化给  CommonsMutipartResolver(Spring自身的多部分解析器）
				CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
						request.getSession().getServletContext());
				if(multipartResolver.isMultipart(request)) {
					//将request变成多部分request
					MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
					//获取multiRequest 中所有的文件名
					Iterator iter=multiRequest.getFileNames();

					while(iter.hasNext()) {
						//一次遍历所有文件
						MultipartFile file=multiRequest.getFile(iter.next().toString());
						if(file!=null && !StringUtil.isEmptyString(file.getOriginalFilename())) {
							fileName = ID.getGuid() + "." + FileHelper.getFileExtName( file.getOriginalFilename());
							String  filePath =  dirPath +fileName;
							//上传
							file.transferTo(new File(filePath));
							result.set("fileName", fileName);
							break;
						}

					}

				}
			} catch (Exception e) {
				LoggerHelper.error(logger, e, "");
				result.setResult(false);
			}
		}

	}



	/**
	 * 上传文件
	 * @param dirPath 文件目录
	 * @param fileName 文件名，不带拓展名
	 * @param httpContext
	 * @param result
	 */
	public void upload(String dirPath,String fileName, HttpContext httpContext, Result result) {
		HttpServletRequest request = httpContext.getRequest();
		HttpSession session = httpContext.getRequest().getSession();
		
		if (!StringUtils.isNotNullAndEmpty(dirPath)) {
			result.setResult(false);
		}
		else{
			try {
				init(request,session);
				List<FileItem> items = (List<FileItem>) upload.parseRequest(request);
				String newFileName="";
				for (FileItem item : items) {
					if (!item.isFormField()) {
						if(StringUtils.isNotNullAndEmpty(item.getName())){
							newFileName = ID.getGuid() + "." + FileHelper.getFileExtName(item.getName());
							item.write(new File(dirPath,newFileName));
							result.set("fileName", newFileName)	;
							
						}
						break;
					}
				}
			} catch (Exception e) {
				LoggerHelper.error(logger, e, "");
				result.setResult(false);
			}
		}
		
	}

	/**
	 * 上传文件
	 * @param dirPath 文件目录
	 * @param fileName 文件名，不带拓展名
	 * @param httpContext
	 * @param result
	 */
	public void upload2(String dirPath,String fileName, HttpContext httpContext, TemplateWord tw,Result result) {
		HttpServletRequest request = httpContext.getRequest();
		HttpSession session = httpContext.getRequest().getSession();

		if (!StringUtils.isNotNullAndEmpty(dirPath)) {
			result.setResult(false);
		}
		else{
			try {
				MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
				init(request,session);
				List<FileItem> items = (List<FileItem>) upload.parseRequest(request);
				String newFileName="";
				for (FileItem item : items) {
					if (!item.isFormField()) {
						if(StringUtils.isNotNullAndEmpty(item.getName())){
							newFileName = ID.getGuid() + "." + FileHelper.getFileExtName(item.getName());
							item.write(new File(dirPath,newFileName));
							tw.setWordName(item.getName());
							tw.setWordGeneratrName(newFileName);
							tw.setWordPath(dirPath+newFileName);

						}
						break;
					}
				}
			} catch (Exception e) {
				LoggerHelper.error(logger, e, "");
				result.setResult(false);
			}
		}

	}


	public void  springUpload2(String dirPath,String fileName, HttpServletRequest request, TemplateWord tw,Result result) {
		if (!StringUtils.isNotNullAndEmpty(dirPath)) {
			result.setResult(false);
		}else{
			try {
				//将当前上下文初始化给  CommonsMutipartResolver(Spring自身的多部分解析器）
				CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
						request.getSession().getServletContext());
				if(multipartResolver.isMultipart(request)) {
					//将request变成多部分request
					MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
					//获取multiRequest 中所有的文件名
					Iterator iter=multiRequest.getFileNames();

					while(iter.hasNext()) {
						//一次遍历所有文件
						MultipartFile file=multiRequest.getFile(iter.next().toString());
						if(file!=null && !StringUtil.isEmptyString(file.getOriginalFilename())) {
							fileName = ID.getGuid() + "." + FileHelper.getFileExtName( file.getOriginalFilename());
							//fileName = file.getOriginalFilename();
							String  filePath =  dirPath +fileName;
							String wordName = file.getOriginalFilename();
							//上传
							String newFileName = "";
							file.transferTo(new File(filePath));
							newFileName = ID.getGuid() + "." +fileName;
							tw.setWordName(wordName);
							tw.setWordGeneratrName(fileName);
							tw.setWordPath(dirPath+fileName);
							break;
						}

					}

				}
			} catch (Exception e) {
				LoggerHelper.error(logger, e, "");
				result.setResult(false);
			}
		}

	}

	
	/**
	 * 添加报告封面与尾页：上传文件---Zhpp
	 * @param dirPath 文件目录
	 * @param httpContext
	 * @param result
	 */
	public void  reportMergeUpload(String dirPath,HttpContext httpContext,Result result) {
		HttpServletRequest request = httpContext.getRequest();
		HttpSession session = httpContext.getRequest().getSession();
		
		if (!StringUtils.isNotNullAndEmpty(dirPath)) {
			result.setResult(false);
		}
		else{
			try {
				init(request,session);
				List<FileItem> items = (List<FileItem>) upload.parseRequest(request);
				String newPath="";
				for (FileItem item : items) {
					if (!item.isFormField()) {
						if(StringUtils.isNotNullAndEmpty(item.getName())){
							result.set("fileName", item.getName());
							String extName = FileHelper.getFileExtName(item.getName());
							newPath = dirPath+ID.getGuid() + "." + extName;
							item.write(new File(newPath));
							
							String tempPath =dirPath +ID.getGuid() + ".pdf" ;
							if("pdf".equals(extName)){
								tempPath = newPath;
							}else{
								ToPdfUtils.fileToPdf(newPath, tempPath);
							}
							result.set("filePath", tempPath);
							
							//返回文档的 web 访问地址
							int	beginIndex = tempPath.indexOf("upfile");  
							if(beginIndex >1){
								beginIndex = beginIndex -1;
							}
							String url=tempPath.substring(beginIndex,tempPath.length());
							result.set("url", url);
						}
						break;
					}
				}
			} catch (Exception e) {
				LoggerHelper.error(logger, e, "");
				result.setResult(false);
			}
		}
		
	}

	/**
	 * 添加报告封面与尾页：上传文件---Zhpp
	 * @param dirPath 文件目录
	 * @param request
	 * @param result
	 */
	public void  springMerge(String dirPath,HttpServletRequest request,Result result) {
		if (!StringUtils.isNotNullAndEmpty(dirPath)) {
			result.setResult(false);
		}else{
			try {
				//将当前上下文初始化给  CommonsMutipartResolver(Spring自身的多部分解析器）
				CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
						request.getSession().getServletContext());
				if(multipartResolver.isMultipart(request)) {
					//将request变成多部分request
					MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
					//获取multiRequest 中所有的文件名
					Iterator iter=multiRequest.getFileNames();

					while(iter.hasNext()) {
						//一次遍历所有文件
						MultipartFile file=multiRequest.getFile(iter.next().toString());
						if(file!=null && !StringUtil.isEmptyString(file.getOriginalFilename())) {
							result.set("fileName", file.getOriginalFilename());
							String extName = FileHelper.getFileExtName(file.getOriginalFilename());
							String newPath = dirPath+ID.getGuid() + "." + extName;
							file.transferTo(new File(newPath));
							String tempPath =dirPath +ID.getGuid() + ".pdf" ;
							if("pdf".equals(extName)){
								tempPath = newPath;
							}else{
								ToPdfUtils.fileToPdf(newPath, tempPath);
							}
							result.set("filePath", tempPath);
							//返回文档的 web 访问地址
							int	beginIndex = tempPath.indexOf("upfile");
							if(beginIndex >1){
								beginIndex = beginIndex -1;
							}
							String url=tempPath.substring(beginIndex,tempPath.length());
							result.set("url", url);
							break;
						}

					}

				}
			} catch (Exception e) {
				LoggerHelper.error(logger, e, "");
				result.setResult(false);
			}
		}

	}

	/**
	 * 上传多个文档
	 * @param filePath 文档目录，多个文档会直接上传到这个目录下面，文件名为32位随机ID
	 * @param httpContext
	 * @param result
	 */
	public void uploads(String filePath, HttpContext httpContext, Result result) {
		HttpServletRequest request = httpContext.getRequest();
		HttpSession session = httpContext.getRequest().getSession();
		File fileDir;
		String path = LogicPathUtil.getSystemUploadPath(StorageFileCacheManage.getSystemUseAddressId());
		if (StringUtils.isNotNullAndEmpty(filePath)) {
			path = path + File.separator + filePath;
		}
		try {
			init(request,session);
			fileDir = new File(path);
			if (!fileDir.exists()) {
				fileDir.mkdirs();
			}
			List<FileItem> items = (List<FileItem>) upload.parseRequest(request);
			String fileName,newFileName;
			for (FileItem item : items) {
				if (!item.isFormField()) {
					fileName = item.getName();
					newFileName = ID.getGuid() + "." + FileHelper.getFileExtName(fileName);
					item.write(new File(path,newFileName));
					result.set(fileName, path + newFileName);
				}
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			result.setResult(false);
		}
	}

	public void download(String url, String fileName, HttpContext httpContext, Result result) {
		String path = "";
		HttpServletResponse response = httpContext.getResponse();
		OutputStream out = null;
		try {
			out = response.getOutputStream();  
			IDSFileUtils.downLoad(new File(path), out);
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			result.setResult(false);
		} finally {
		}
	}
	
	
}
